//
//  OnRoadTableViewController.m
//  TravelToHelp
//
//  Created by lanou3g on 15/11/5.
//  Copyright © 2015年 冯贵宾. All rights reserved.
//

#import "OnRoadTableViewController.h"
#import "ClassifyView.h"
#import "JokeModel.h"
#import "OnRoadTableViewCell.h"
//#import "UITableView+EmptyData.h"
#import "VoiceTableViewController.h"
#import "RadioTableViewController.h"


@interface OnRoadTableViewController ()

@property (nonatomic, strong) ClassifyView *classifyView;
@property (nonatomic, strong) NSMutableArray *dataArray;

@end

@implementation OnRoadTableViewController


#pragma mark - life cycle -

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"在路上";
    
    [self addClassifyView];
    [self setUpData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - delegate -


#pragma mark - event response -
//- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    VoiceTableViewController *voiceVC = [[VoiceTableViewController alloc] init];
//    [self.navigationController pushViewController:voiceVC animated:YES];
//}

- (void)actionJumpToClassifyView:(UIButton *)sender
{
    VoiceTableViewController *voiceVC = [[VoiceTableViewController alloc] init];
    
    RadioTableViewController *radioVC = [[RadioTableViewController alloc] init];
    
    if ([sender isEqual: self.classifyView.voiceBtn]) {
    [self.navigationController pushViewController:voiceVC animated:YES];
    } else
//        if (self.classifyView.radioBtn)
        {
        [self.navigationController pushViewController:radioVC animated:YES];
    }
}

- (void)actionJumpToRadioView:(UIButton *)sender
{
    RadioTableViewController *radioVC = [[RadioTableViewController alloc] init];
    
    [self.navigationController pushViewController:radioVC animated:YES];
    
}

#pragma mark - methods -
- (void)setUpData
{
 
    NSString *urlStr = @"http://c.3g.163.com/recommend/getChanRecomNews?channel=duanzi&passport=f1695d5eafd30a48a60d2539c145248f@tencent.163.com&devId=28591CD8-BE83-4835-B4C7-FE286B77F8AB&size=20";
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlStr] cachePolicy:(NSURLRequestUseProtocolCachePolicy) timeoutInterval:15];
    
    NSURLSessionConfiguration *config = [NSURLSessionConfiguration ephemeralSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error) {
            
            //[self tableViewDisplayWitMsg:@"没有查询到相对应的商品" ifNecessaryForRowCount:self.dataArray.count];
            NSLog(@"Httperror: %@%ld", error.localizedDescription, error.code);
            return;
        } else {
            self.dataArray = [NSMutableArray array];
            NSDictionary *tempDict = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
            NSMutableArray *tempArr = [tempDict valueForKey:@"段子"];
            for (NSDictionary *dic in tempArr) {
                JokeModel *model = [[JokeModel alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                //NSLog(@"%@", model.img);
                [self.dataArray addObject:model];
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableView reloadData];
            });
        }
    }];
    
    [dataTask resume];
}

#pragma mark - setters and getters -
- (void)addClassifyView
{
    self.tableView.contentInset = UIEdgeInsetsMake(80, 0, 0, 0);
    self.classifyView = [[ClassifyView alloc] initWithFrame:CGRectMake(0, -80, kScreenWidth, 80)];
    self.classifyView.backgroundColor = [UIColor purpleColor];
    
    [self.classifyView.voiceBtn addTarget:self action:@selector(actionJumpToClassifyView:) forControlEvents:(UIControlEventTouchUpInside)];
    
    [self.classifyView.radioBtn addTarget:self action:@selector(actionJumpToClassifyView:) forControlEvents:UIControlEventTouchUpInside];
    [self.tableView addSubview:self.classifyView];
}



#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //UITableViewCell *cell =[self tableView:self.tableView cellForRowAtIndexPath:indexPath];
//    return cell.frame.size.height;
    return 200;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *joke = @"joke";
    OnRoadTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:joke];
    if (cell == nil) {
        cell = [[OnRoadTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:joke];
    }
    if (self.dataArray.count > 0) {
        JokeModel *model = self.dataArray[indexPath.row];
        cell.titleTXT.text = model.title;
        cell.titleDetailTXT.text = model.digest;
        [cell.IMGView sd_setImageWithURL:[NSURL URLWithString:model.img]];
        if (model.img == nil) {
            //[cell delete:cell.IMGView];
        }
    }
    
    return cell;
}

//自适应高度





/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end



//@implementation UITableView (EmptyData)
//
//- (void) tableViewDisplayWitMsg:(NSString *) message ifNecessaryForRowCount:(NSUInteger) rowCount
//{
//    if (rowCount == 0) {
//        // Display a message when the table is empty
//        // 没有数据的时候，UILabel的显示样式
//        UILabel *messageLabel = [UILabel new];
//        
//        messageLabel.text = message;
//        messageLabel.font = [UIFont preferredFontForTextStyle:UIFontTextStyleBody];
//        messageLabel.textColor = [UIColor lightGrayColor];
//        messageLabel.textAlignment = NSTextAlignmentCenter;
//        [messageLabel sizeToFit];
//        
//        self.backgroundView = messageLabel;
//        self.separatorStyle = UITableViewCellSeparatorStyleNone;
//    } else {
//        self.backgroundView = nil;
//        self.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
//    }
//}
//
//
//@end
//


